package com.flynn.rock.handler;

import com.flynn.rock.enums.BusinessType;
import com.flynn.rock.enums.OperateType;
import com.flynn.rock.model.Response;
import com.flynn.rock.model.dto.OperateLogDto;
import com.flynn.rock.model.dto.system.UserAccountDto;
import com.flynn.rock.system.api.ISysOperateLogApi;
import com.flynn.rock.util.HttpServletUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class SysLogoutSuccessHandler implements LogoutSuccessHandler {

    @Resource
    private ISysOperateLogApi sysOperateLogApi;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
                                Authentication authentication) throws IOException, ServletException {
        this.handleOperateLog(request, authentication);
        HttpServletUtil.response(response, Response.success(authentication), HttpStatus.OK);
    }

    private void handleOperateLog(HttpServletRequest request, Authentication authentication) {
        if (authentication.getPrincipal() instanceof UserAccountDto userDetails) {
            OperateLogDto dto = new OperateLogDto();
            String ip = HttpServletUtil.getIp(request);
            dto.setOperateIp(ip);
            dto.setRequestMethod(request.getMethod());
            dto.setOperateAddress(HttpServletUtil.getCityInfo(ip));
            dto.setOperateTitle("退出登录");
            dto.setOperateType(OperateType.LOGOUT);
            dto.setBusinessType(BusinessType.SYSTEM);
            dto.setOperateUserId(userDetails.getUserId());
            dto.setOperateUserName(userDetails.getUser().getRealName());
            dto.setOperateDeptId(userDetails.getUser().getDeptId());
            dto.setConsumeTime(10L);
            dto.setRequestUrl("/api/sys/logout");
            dto.setStatus("INFO");
            sysOperateLogApi.saveOperateLog(dto);
        }
    }
}
